package prometheus

import (
	"fmt"
	"time"

	"github.com/valyala/fasthttp"
)

type Matrix struct {
	Name  string
	Unit  string
	Value int64
}

type MatrixSet struct {
	Proc    string
	Matrixs map[string][]Matrix
}

func NewMatrixSet(proc string) *MatrixSet {
	return &MatrixSet{
		Proc:    proc,
		Matrixs: make(map[string][]Matrix),
	}
}

func (ms *MatrixSet) UpdateMatrix(m map[string]int64, unit string, name string) {
	ms.Matrixs[name] = make([]Matrix, 0)
	for key, value := range m {
		matrix := Matrix{
			Name:  key,
			Value: value,
			Unit:  unit,
		}
		ms.Matrixs[name] = append(ms.Matrixs[name], matrix)
	}
}

func (ms *MatrixSet) toString() string {
	var buff string
	timestamp := time.Now().UnixNano() / 1000 / 1000
	proc := ms.Proc
	matrixs := ms.Matrixs
	for name, v := range matrixs {
		str := fmt.Sprintf("# TYPE %s gauge", name)
		buff = buff + str + "\n"
		for _, m := range v {
			str := fmt.Sprintf(`%s{proc_name="%s",m="%s",u="%s"} %v %v`,
				name, proc, m.Name, m.Unit, m.Value, timestamp)
			buff = buff + str + "\n"
		}
	}
	return buff
}

func (ms *MatrixSet) ListenPrometheus(addr string) {
	fasthttp.ListenAndServe(addr, func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Path()) {
		case "/export":
			ctx.Success("text/plain", []byte(ms.toString()))
		}
	})
}
